package com.gzs.learn.payment.pay.action;

import com.google.common.collect.Maps;
import com.gzs.learn.common.util.JsonUtil;
import com.gzs.learn.inf.BaseResponseDto;
import com.gzs.learn.payment.pay.ActionEnum;
import com.gzs.learn.payment.pay.ContextBase;
import com.gzs.learn.payment.pay.PaymentContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

import static com.gzs.learn.common.util.SpringContextUtil.getBean;

@Component
@Slf4j
public class ActionInvoker {
    private final Map<ActionEnum, BaseAction> actions = Maps.newConcurrentMap();

    @PostConstruct
    public void init() {
        actions.put(ActionEnum.PAYMENT, getBean(PaymentAction.class));
        actions.put(ActionEnum.PAYMENT_QUERY, getBean(PaymentQueryAction.class));
        actions.put(ActionEnum.PAYMENT_CALLBACK, getBean(PaymentCallbackAction.class));
        actions.put(ActionEnum.PAYMENT_NOTIFY, getBean(PaymentNotifyAction.class));
        actions.put(ActionEnum.CLOSE, getBean(CloseAction.class));
        actions.put(ActionEnum.REFUND, getBean(RefundAction.class));
        actions.put(ActionEnum.REFUND_QUERY, getBean(RefundAction.class));
        actions.put(ActionEnum.REFUND_CALLBACK, getBean(RefundCallbackAction.class));
        actions.put(ActionEnum.REFUND_NOTIFY, getBean(RefundNotifyAction.class));
    }

    public BaseResponseDto<?> invoke(PaymentContext<ContextBase> paymentContext) {
        ActionEnum actionEnum = paymentContext.getActionEnum();
        BaseAction baseAction = actions.get(actionEnum);
        if (baseAction == null) {
            log.warn("action:{} is null,context:{}", actionEnum, JsonUtil.toJSONString(paymentContext));
            return null;
        }
        // 初始化DB中必要的参数信息
        baseAction.initBaseContext(paymentContext);
        BaseResponseDto<?> responseDto = baseAction.executeAction(paymentContext);
        return responseDto;
    }
}
